<template>
    <MenuPage 
    :data="videoList" 
    :columns="columns"
    :page.sync="videoPage"
    :size.sync="videoPageSize"
    :total="videoTotal"
    :loading="tableLoading"
    @queryFun="getFileList">
      <template slot="search">
          <Button type="primary" ghost icon="ios-cloud-upload-outline" @click="showModalBtn"
            >上传{{ pageTitle }}</Button
          >
          <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
          <div style="height: 32px;line-height: 32px;margin:0 15px">
            <Checkbox v-model="uploadByMe" @on-change="searchUploadByMe" style="width: 70px;"
              >由我创建</Checkbox
            >
          </div>
          <i-select
            clearable
            v-model="selectFileType"
            placeholder="文件类型"
            style="width: 150px;margin-left: 15px"
            @on-change="selectFileTypeChange"
          >
            <i-option value="image">图片</i-option>
            <i-option value="video">视频</i-option>
            <i-option value="docs">文档</i-option>
            <i-option value="audios">音频</i-option>
            <i-option value="relay">glb</i-option>
            <i-option value="files">其他</i-option>
          </i-select>
          <i-select
            clearable
            placeholder="可见范围"
            style="width: 150px;margin-left: 15px "
            v-model="ispublic"
            @on-change="getFileList"
          >
            <i-option value="range">平台</i-option>
            <i-option value="system">系统</i-option>
            <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
          </i-select>
          <Input
            v-model.trim="fileInput"
            placeholder="文件名称"
            clearable
            @on-change="searchFile"
            style="width: 180px;margin-left: 15px;"
          />
          <Button
            class="header-btn"
            type="primary"
            ghost
            style="height: 32px;margin-left: 5px;"
            @click="refreshFile()"
            ><i class="el-icon-refresh-right"
          /></Button>
      </template>
    <Modal v-model="pdfModal" title="pdf预览" width="60" :mask-closable="false" footer-hide>
      <!--<iframe src="http://172.18.100.4:18769/api/viewer/document/F495148a-a7ca-49a3-8035-d83c752a90f1" width="100%" height="600px" ></iframe>-->
      <iframe :src="pdfUrl" width="100%" height="600px" scrolling="none" frameborder="0"></iframe>
    </Modal>

    <!--上传文件-->
    <Modal
      v-model="uploadFileModal"
      :mask-closable="false"
      width="500"
      :closable="false"
      :footer-hide="true"
      :title="`上传${pageTitle}`"
    >
      <!-- <div class="uploadTypeWrap">
                支持上传类型：<Tooltip :content="formatStr" placement="top-start" width="200">
                    <Icon type='ios-help-circle' color='rgb(255, 153, 0)' />
                </Tooltip>
               <p>文件名称:只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符</p>
            </div> -->
      <Form ref="formItem" :model="formItem" :rules="formItemRule" :label-width="80">
        <FormItem label="可见范围" prop="visibility">
          <RadioGroup v-model="formItem.visibility">
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="上传文件" prop="file">
          <Upload ref="uploadFile" :action="upLoadUrl" :before-upload="handleUploadIcon">
            <Button icon="ios-cloud-upload-outline" :disabled="loading">选择文件</Button>
          </Upload>
          <Poptip
            class="too"
            popper-class="tooltipclass"
            theme="dark"
            placement="top"
            width="400"
            :transfer="true"
            trigger="hover"
          >
            <Icon type="ios-alert" class="ios-alert" />
            <div class="api" slot="content">
              <p style="white-space: normal;word-break: break-all;">支持上传类型:{{ formatStr }}</p>
              <p style="white-space: normal;">
                文件名称:只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符
              </p>
            </div>
          </Poptip>
          <div v-if="formItem.file !== null">
            <p>文件名: {{ formItem.file.name }}</p>
            <p>大小：<span v-text="fileSize"></span></p>
            <Progress :percent="progress"></Progress>
            <p>速度：<span v-text="speed"></span></p>
          </div>
        </FormItem>
        <!--<FormItem label="图片类型" prop="bucket" v-if="showSelectBucket">
                    <RadioGroup v-model="formItem.bucket">
                        <Radio label="exp-img">课件图片</Radio>
                        <Radio label="course-img">课程图片</Radio>
                        <Radio label="guideImg">指导书图片</Radio>
                        <Radio label="images">其他</Radio>
                    </RadioGroup>
                </FormItem>-->
        <FormItem>
          <Button type="primary" @click="formBtn('formItem')" :loading="loading">确定</Button>
          <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="uploadShow"
      title="关闭提示"
      width="300"
      :mask-closable="false"
      :closable="false"
      @on-ok="YesOk"
      @on-cancel="NoCancel"
    >
      <p>关闭对话框，可能导致上传失败，是否关闭？</p>
    </Modal>
  <!-- </div>
   -->
  </MenuPage>
</template>
<script>
// function getSize(val) {
//   let type = '';
//   if (val > 1024 * 1024) {
//     val = val / (1024 * 1024);
//     type = ' MB';
//   } else {
//     val = val / 1024;
//     type = ' KB';
//   }
//   val = val.toFixed(2);
//   return val + '' + type;
// }
import $ from 'jquery';
import cookieUse from '@/libs/cookie.js';
import encryption from '@/libs/encryption.js';
import { getFilesData, delFile } from '@/api/uploadFile.js';
import { debounce } from '@/libs/utils';
import pageTitle from '@/mixin/pageTitle';
export default {
  mixins: [pageTitle],
  components: {},
  data() {
    const validateUpload = (rule, value, callback) => {
      if (this.formItemRule.file === null) {
        callback(new Error('Please select the file to upload'));
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      // 显示
      showDataList: true,
      showDefImg: false,
      // 过滤
      uploadByMe: false,
      // 文件列表
      videoPage: 1,
      videoPageSize: 12,
      videoList: [],
      columns : [
        {
          title: '文件名',
          key: 'originName',
          minWidth:100,
          tooltip:true
        },
        {
          title: '文件类型',
          key: 'bucket',
          filter:this.filterFileType
        },
        {
						title: '可见范围',
						key: 'visibility',
						minWidth:100,
            render:(h,params) => {
              return h('span',{
                style:{
                  color:this.setVisibility(params.row.visibility).color
                }
              },this.setVisibility(params.row.visibility).text)
            }
					},
        {
          title: '文件大小',
          key: 'size',
          filter:this.getSize,
          minWidth:100,
          tooltip:true
        },
        {
          title: '时长',
          key: 'time',
          filter:(time,item) => {
            return this.getTimes(item)
          },
          minWidth:100,
          tooltip:true
        },
        {
          title: '创建时间',
          key: 'created'
        },
        {
          title: '操作',
          key: 'action',
          opList:[
	          {
              txt:'下载',
              type:'download',
              on:{
                click:(data,e) => {
                  this.downInfo(data)
                }
              }
            },
            {
              txt:'查看',
              type:'check',
              disabled:(data) => {
                return this.isDisabledType(data.bucket,data.originName)
              },
              on:{
                click:(data,e) => {
                  this.checkInfo(data)
                }
              }
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个文件吗？',
              disabled: (data) => {
                return this.setIsClick(data) ? true :false
              },
              on: {
                click: (data,e) => {
                  this.deleteVideo(data)
                }
              }
            }
          ]
        },
      ],
      videoTotal: 0,
      // 搜索 图片视频
      fileInput: '',
      selectFileType: 'all',
      searchFileType: '',
      // 上传路径
      upLoadUrl: ``,
      setUpLoadHead: { Authorization: cookieUse.getCookie('desig-token') },
      progressPercent: 0,
      showProgress: false,
      // 上传
      uploadFileModal: false,
      formItem: {
        visibility: 'share',
        file: null,
        bucket: ''
      },
      formItemRule: {
        visibility: [{ required: true, message: 'Please select ispublic', trigger: 'change' }],
        file: [{ required: true, validator: validateUpload, trigger: 'change' }],
        bucket: [{ required: true, message: 'Please select ispublic', trigger: 'change' }]
      },
      ispublic: '',
      formatStr: '',
      formatArr: [
        'xz',
        'bin',
        'dmp',
        'dms',
        'rmvb',
        'midi',
        'exe',
        'xml',
        'jar',
        'qxd',
        'wks',
        'ram',
        'zip',
        'rar',
        'apr',
        'ac',
        '7z',
        'mpg',
        'lnk',
        'png',
        'eps',
        'ott',
        'ra',
        '123',
        'au',
        'dwg',
        'aw',
        'doc',
        'odp',
        'rm',
        'odt',
        'nsf',
        'aac',
        'lwp',
        'log',
        'vsd',
        'flac',
        'dot',
        'mid',
        'wma',
        'mif',
        'cmx',
        'wmf',
        'arc',
        'vcd',
        'epub',
        'pgm',
        'vcf',
        'kmz',
        'jpeg',
        '3gp',
        'mar',
        'xlsx',
        'ntf',
        'wmv',
        'fli',
        'wmz',
        'rtf',
        'fdf',
        'docx',
        'xpi',
        'flv',
        'pps',
        'asf',
        'ppt',
        'kwd',
        'cod',
        'xps',
        'com',
        'msf',
        'msi',
        'swf',
        'iso',
        'bmp',
        'asx',
        'oga',
        'hqx',
        'ogg',
        'p10',
        'rmi',
        'tif',
        'ico',
        'mkv',
        'sxd',
        'sxc',
        'ogv',
        'prc',
        'ogx',
        'sxi',
        'cpt',
        'xar',
        'spf',
        'chm',
        'wpd',
        'mdb',
        'webp',
        'adp',
        'webm',
        'gpx',
        'spl',
        'pptx',
        'sxw',
        'mdi',
        'wps',
        'psd',
        'tiff',
        'eml',
        'aiff',
        'cab',
        'gif',
        'mmf',
        'fm',
        'vob',
        'caf',
        'rgb',
        'cap',
        'dtd',
        'avi',
        'cat',
        'sil',
        'm4a',
        'bz2',
        'class',
        'jpe',
        'sit',
        'jpg',
        'pcx',
        'dll',
        'org',
        'ttf',
        'xla',
        'hlp',
        'wav',
        'm4v',
        'pdb',
        'wri',
        'mp4',
        'mp3',
        'pdf',
        'obj',
        'pls',
        'csh',
        'mny',
        'pub',
        'xls',
        'dmg',
        'glb',
        'txt',
        'json',
        'md'
      ],
      //              formatArr:["jpeg","jpg","jpe","png","gif","tiff","bmp","dwg","psd","ico","rgb","ogx","pcx","mdi","tif","pgm","cmx","webp","pdf","doc","docx","xls","xlsx",
      //              	"xla","pptx","pps","ppt","rtf","zip","bz2","7z","cab","rar","epub","mp4","webm","ogv","ogg","3gp","3g2","m4v","mpg","vob","fli","mkv","asf","asx","wmv",
      //              	"flv","avi","m4a","sil","ra","ram","au","wma","aiff","mp3","mid","midi","rmi","oga","wav","caf","flac","adp","aac"],
      speed: 0,
      loaded: 0,
      fileSize: 0,
      progress: 0,
      loading: false,
      downLoadImg: require('../../assets/project/download-h.png'),
      checkIcon: require('../../assets/project/magnifier-h.png'),
      checkIconDisabled: require('../../assets/project/magnifier-s.png'),
      pdfUrl: '',
      pdfModal: false,
      showSelectBucket: false, //是否需要选择桶
      uploadShow: false, //上次时关闭对话框提示
      updataLoading: true,
      isUpdataing: false, //判断是否在上传中,
      tableLoading: true
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.upLoadUrl = `${this.baseURL}/minio/upload/permanent`; //${this.baseURL}/ftp/edu-ftp/upload/${November.userId}
  },
  mounted() {
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    // 列表
    this.getFileList();
    this.formatStr = this.formatArr.toString();
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.contentHei = this.fullHeight - 197; // 80是头部高度  60是上下padding
      this.videoPageSize = Math.floor(this.contentHei / 96);
    },
    // 文件列表
    getFileList() {
      this.showDefImg = true;
      this.showDataList = false;
      this.tableLoading = true;
      let params = {
        pageIndex: this.videoPage,
        pageSize: this.videoPageSize
      };
      let data = {
        //              	originName:this.fileInput,
        //                  type:this.searchFileType,
        //                  sortBy:'File_Time',
        //                  order:'desc',
        //                  visibility : this.ispublic
      };
      if (this.uploadByMe) {
        // params.isPublic = 0
        data.creator = this.USER_ID;
      }
      if (this.fileInput) {
        data.originName = this.fileInput;
      }
      if (this.searchFileType) {
        data.bucket = this.searchFileType;
      }
      if (this.ispublic) {
        data.visibility = this.ispublic;
      }
      getFilesData(params, data)
        .then((res) => {
          if (res.data.code == 1) {
            let attribute = res.data.data;
            let items = attribute.list;
            this.videoTotal = attribute.total;
            this.videoList = items;
            if (items.length > 0) {
              this.showDefImg = false;
              this.showDataList = true;
            } else {
              this.showDefImg = true;
              this.showDataList = false;
            }
          } else {
            this.showDefImg = true;
            this.showDataList = false;
          }
          this.tableLoading = false;
        })
        .catch((err) => {
          this.showDefImg = true;
          this.showDataList = false;
          console.log(err);
          this.tableLoading = false;
        });
    },
    videoOnChange(val) {
      this.videoPage = val;
      this.getFileList();
    },
    confirmEnding(str, target) {
      var start = str.length - target.length;
      var arr = str.substr(start, target.length);
      if (arr == target) {
        return true;
      }
      return false;
    },
    isDisabledType(type, name) {
      let list = name.split('.');
      let lastStr = list
        .pop()
        .trim()
        .toLowerCase();
      if (list.length < 1) {
        // 没有后缀名需要禁用
        return true;
      } else {
        let othersArr = ['zip', 'bz2', '7z', 'cab', 'rar', 'epub']; // 需要被禁用的类型
        return othersArr.includes(lastStr);
      }
    },
    checkInfo(params) {
      if (this.isDisabledType(params.bucket, params.originName)) {
        // 这两种类型不支持预览，不需要打开预览页面
        return;
      }
      let path = params.path;
      if (params.originName.endsWith('.md')) {
        let href = this.$router.resolve({
          name: 'mdPreview',
          query: {
            path: path,
            name: params.originName
          }
        }).href;
        window.openTrain(href, '_blank');
      } else {
        window.openTrain(`/api/minio/filePreview?path=${path}`);
      }
      // let fileId = params.id;
      // let path = params.path;
      // window.openTrain(`/api/minio/filePreview?path=${path}`);
      return;
      if (params.fileCatalog == 'docs') {
        let fileName = params.fileName;
        if (this.confirmEnding(fileName, 'pdf')) {
          //pdf文档用直接展示
          window.openTrain(`/Learn/${path}`);
        } else {
          //word文档转pdf展示
          let reviewUrl = `/api/minio/viewer/document/${fileId}`; //ftp/edu-ftp/viewOnline/pdf/${fileId}
          this.pdfUrl = `static/pdfjs/web/viewer.html?file=${encodeURIComponent(reviewUrl)}`;
          this.pdfModal = true;
        }
      } else if (params.fileCatalog == 'files') {
        //压缩文档下载
        window.openTrain(`/api/ftp/edu-ftp/download?id=${fileId}`);
      } else {
        //其他展示
        // window.openTrain(`/Learn/${path}`);
        window.openTrain(`/api/minio/filePreview?path=${path}`);
      }
    },
    downInfo(params) {
      let fileId = params.id;
      let path = params.path;
      window.openTrain(`/api/minio/download/${fileId}`);
    },
    searchFile(val) {
      this.videoPage = 1;
      this.fileInput = this.fileInput;
      this.getFileList();
    },
    selectFileTypeChange(val) {
      this.videoPage = 1;
      if (!val) {
        this.searchFileType = '';
      } else if (val == 'image') {
        this.searchFileType = 'images';
      } else if (val == 'video') {
        this.searchFileType = 'videos';
      } else if (val == 'docs') {
        this.searchFileType = 'docs';
      } else if (val == 'audios') {
        this.searchFileType = 'audios';
      } else if (val == 'files') {
        this.searchFileType = 'files';
      } else if (val == 'relay') {
        this.searchFileType = 'relay';
      }
      this.getFileList();
    },
    searchUploadByMe(val) {
      this.videoPage = 1;
      this.getFileList();
    },
    refreshFile() {
      this.videoPage = 1;
      this.fileInput = '';
      this.ispublic = '';
      this.selectFileType = 'all';
      this.searchFileType = '';
      this.uploadByMe = false;
      this.getFileList();
    },
    // 删除
    deleteVideo(params) {
      if (
        params.visibility === 'public' ||
        params.hidden == 1 ||
        (params.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        this.$Message.info({
          content: '没有权限！',
          duration: 3
        });
        return false;
      }
      let fileId = params.id;
      delFile(fileId)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '删除成功！',
              duration: 3
            });
            this.videoPage =
              this.videoPage > 1 && this.videoList.length === 1
                ? this.videoPage - 1
                : this.videoPage;
            this.getFileList();
          } else {
            this.$Message.error('删除失败！');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 上传成功
    upLoadSuccess(response, file, fileList) {
      if (response.code == 1) {
        this.showProgress = false;
        this.$Message.success('上传成功');
        this.getFileList();
      } else {
        this.showProgress = false;
        this.$Message.error({
          content: response.message,
          duration: 3
        });
      }
    },
    // 上传失败
    upLoadErr(error, file, fileList) {
      this.$Message.error('上传失败');
    },
    // 视频上传时的钩子
    upLoadProgress(event, file, fileList) {
      let percent = event.percent;
      percent = percent.toFixed(1);
      this.progressPercent = parseInt(percent);
    },
    // 上传前
    beforeUpload(file) {
      if (file) {
        this.showProgress = true;
      }
    },

    // 上传文件 2020/03/27 新
    showModalBtn() {
      this.uploadFileModal = true;
      this.loading = false;
      this.formItem.visibility = 'share';
      this.formItem.file = null;
      this.showSelectBucket = false;
      this.speed = 0;
      this.loaded = 0;
      this.fileSize = 0;
      this.progress = 0;
    },
    getFileName(name) {
      return name.substring(0, name.lastIndexOf('.'));
    },
    handleUploadIcon(file) {
      this.speed = 0;
      this.loaded = 0;
      this.progress = 0;
      this.isUpdataing = true;
      this.onlyFileName = file.name + '_' + new Date().getTime();
      if (file) {
        if (file.size > 1024 * 1024) {
          this.fileSize = (Math.round((file.size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
        } else {
          this.fileSize = (Math.round((file.size * 100) / 1024) / 100).toString() + 'KB';
        }
        //验证名称
        if (file.name) {
          let name = this.getFileName(file.name);
          // let reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
          let reg = new RegExp('/[\\/:*?"<>|]/gi');
          if (reg.test(name) || name.length > 64) {
            this.$Message.error({
              content: '文件名称不能包含下列任意英文字符 \ / : * ? " < > |，名称长度为1-64个字符',
              duration: 3
            });
            return false;
          }
        }
      }
      let exceededNum = file.name.lastIndexOf('.');
      let exceededStr = file.name
        .substring(exceededNum + 1, file.name.length)
        .trim()
        .toLowerCase();
      if (exceededStr && this.formatArr.indexOf(exceededStr) > -1) {
        this.formItem.file = file;
        let imageArr = [
          'jpeg',
          'jpg',
          'jpe',
          'png',
          'gif',
          'tiff',
          'bmp',
          'dwg',
          'psd',
          'ico',
          'rgb',
          'ogx',
          'pcx',
          'mdi',
          'tif',
          'pgm',
          'cmx',
          'webp'
        ];
        let docsArr = [
          'pdf',
          'doc',
          'docx',
          'xls',
          'xlsx',
          'xla',
          'pptx',
          'pps',
          'ppt',
          'rtf',
          'txt',
          'md'
        ];
        let othersArr = ['zip', 'bz2', '7z', 'cab', 'rar', 'epub'];
        let videoArr = [
          'mp4',
          'webm',
          'ogv',
          'ogg',
          '3gp',
          '3g2',
          'm4v',
          'mpg',
          'vob',
          'fli',
          'mkv',
          'asf',
          'asx',
          'wmv',
          'flv',
          'avi'
        ];
        let audioArr = [
          'm4a',
          'sil',
          'ra',
          'ram',
          'au',
          'wma',
          'aiff',
          'mp3',
          'mid',
          'midi',
          'rmi',
          'oga',
          'wav',
          'caf',
          'flac',
          'adp',
          'aac'
        ];
        this.showSelectBucket = false;
        if (imageArr.includes(exceededStr)) {
          this.showSelectBucket = true;
          this.formItem.bucket = 'images';
          this.formItem.type = 'images';
        } else if (docsArr.includes(exceededStr)) {
          this.formItem.bucket = 'docs';
          this.formItem.type = 'docs';
        } else if (othersArr.includes(exceededStr)) {
          this.formItem.bucket = 'files';
          this.formItem.type = 'files';
        } else if (videoArr.includes(exceededStr)) {
          this.formItem.bucket = 'videos';
          this.formItem.type = 'videos';
        } else if (audioArr.includes(exceededStr)) {
          this.formItem.bucket = 'audios';
          this.formItem.type = 'audios';
        } else if (exceededStr == 'glb') {
          this.formItem.bucket = 'relay';
          this.formItem.type = 'glb';
        } else {
          this.formItem.bucket = 'files';
          this.formItem.type = 'files';
        }
        return false;
      } else {
        this.uploadFile = null;
        this.formItem.file = '';
        this.formItem.bucket = '';
        this.formItem.type = '';
        this.$Message.error({
          content: '不支持当前文件类型',
          duration: 3
        });
        return false;
      }
    },
    formBtn(name) {
      let _this = this;
      let isPublic = '';
      if (!this.formItem.file) {
        _this.$Message.warning({
          content: '请先选择文件！',
          duration: 2
        });
        return;
      }

      //              if(this.formItem.visibility === '0' || this.formItem.visibility === 0){
      //                  isPublic = '?visibility=0'
      //              }else{
      //              	isPublic = '?visibility=1'
      //              }
      this.$refs[name].validate((valid) => {
        if (valid) {
          let formData = new window.FormData();
          formData.append('file', _this.formItem.file);
          let file = {
            name: this.onlyFileName //this.formItem.file.name
          };
          _this.loading = true;
          _this
            .axios({
              method: 'post',
              url: `${_this.upLoadUrl}?visibility=${this.formItem.visibility}&bucket=${this.formItem.bucket}&type=${this.formItem.type}`,
              data: formData,
              headers: {
                'Content-type': 'multipart/form-data'
              },
              timeout:0,
              onUploadProgress: (progressEvent) => {
                //解决上传过程中关闭了modal,再选择文件，会显示上次上传的进度级速度问题
                if (file.name && _this.onlyFileName && file.name != _this.onlyFileName) {
                  return;
                }
                var complete = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
                _this.progress = complete;
                function getspeed() {
                  var aaspeed = Number(progressEvent.loaded - _this.loaded);
                  _this.loaded = progressEvent.loaded;
                  if (aaspeed > 1024 * 1024) {
                    _this.speed =
                      (Math.round((aaspeed * 100) / (1024 * 1024)) / 100).toString() + 'MB/s';
                  } else {
                    _this.speed = (Math.round((aaspeed * 100) / 1024) / 100).toString() + 'KB/s';
                  }
                }
                setInterval(getspeed(), 1000);
              }
            })
            .then((res) => {
              if (res.data.code == 1) {
                _this.formItem.file = null;
                if (_this.progress === 100) {
                  _this.$Message.success({
                    content: '创建成功！',
                    duration: 2
                  });
                }
                setTimeout(() => {
                  _this.loading = false;
                  this.uploadFileModal = false;
                  this.isUpdataing = false;
                  this.uploadShow = false;
                  // this.exGroupHandleReset('formItem')
                  //this.getFileList()
                  this.refreshFile();
                }, 2000);
              } else {
                _this.loading = false;
                this.formItem.file = null;
                this.speed = 0;
                this.loaded = 0;
                this.fileSize = 0;
                this.progress = 0;
                this.isUpdataing = false;
                this.uploadShow = false;
                _this.$Message.error({
                  content: res.data.message,
                  duration: 3
                });
              }
            })
            .catch((err) => {
              console.log(err);
              _this.$Message.error('服务器连接失败！');
              _this.loading = false;
            });
        } else {
          _this.$Message.error('请完善信息！');
        }
      });
    },
    // 计算index
    handleProIndex(key) {
      return (this.videoPage - 1) * this.videoPageSize + key + 1;
    },
    getSize(val) {
      let type = '';
      if (val > 1024 * 1024) {
        val = val / (1024 * 1024);
        type = ' MB';
      } else {
        val = val / 1024;
        type = ' KB';
      }
      val = val.toFixed(2);
      return val + '' + type;
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 'company') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 'person') {
        text = '个人';
        color = '#FFA500';
      } else if (val === 'system') {
        text = '系统';
        color = '#4169E1';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    // 时长
    getTimes(item) {
      if (item.bucket == 'videos' || item.bucket == 'audios') {
        let mss = item.duration;
        if (item.duration == 0) {
          return item.duration;
        }
        let days = parseInt(mss / (1000 * 60 * 60 * 24));
        let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = (mss % (1000 * 60)) / 1000;
        let time = '';
        if (hours > 0) {
          time += hours + ' 时 ';
        }
        if (minutes > 0) {
          time += minutes + ' 分';
        }
        if (seconds > 0) {
          time += seconds + ' 秒 ';
        }
        return time;
      } else {
        return '-';
      }
    },
    // 设置知否可点击
    setIsClick(item) {
      if (
        item.visibility === 'public' ||
        item.hidden == 1 ||
        (item.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        return { 'pointer-events': 'none' };
      }
    },
    setDelImgSrc(item) {
      if (
        item.visibility === 'public' ||
        item.hidden == 1 ||
        (item.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    handleImage(logo) {
      let src = '';
      if (logo) {
        if (logo.indexOf('Learn') > -1) {
          src = logo;
        } else {
          src = `/Learn/${logo}`;
        }
      } else {
        //                  src = this.defaultImg
      }
      return src;
    },
    changeModalLoading() {
      this.updataLoading = false;
      this.$nextTick(() => {
        this.updataLoading = true;
      });
    },
    cancelUpload() {
      //关闭上传给出提示
      let _this = this;
      if (_this.isUpdataing) {
        _this.uploadShow = true;
        _this.changeModalLoading();
      } else {
        this.uploadFileModal = false;
      }
    },
    YesOk() {
      this.uploadShow = false;
      this.uploadFileModal = false;
      this.isUpdataing = false;
    },
    NoCancel() {
      this.uploadShow = false;
    },
    filterFileType(type) {
      let str;
      switch (type) {
        case 'images':
          str = '图片';
          break;
        case 'videos':
          str = '视频';
          break;
        case 'docs':
          str = '文档';
          break;
        case 'audios':
          str = '音频';
          break;
        case 'relay':
          str = 'glb';
          break;
        case 'toolkit':
          str = '工具';
          break;
        case 'icon':
          str = '图标';
          break;
        case 'files':
          str = '其他';
          break;
        default:
          str = '其他';
      }
      return str;
    }
  }
};
</script>
<style scoped>
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.uploadTypeWrap {
  color: orange;
  margin-bottom: 16px;
}
.uploadTypeWrap /deep/ .ivu-tooltip-inner {
  word-break: break-all;
  white-space: pre-wrap;
}
</style>
